package com.example.allfilemanagerdemo.utils

import android.app.Activity
import android.app.Application
import android.content.ContentUris
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import com.luck.picture.lib.utils.PictureFileUtils.getDataColumn
import com.luck.picture.lib.utils.PictureFileUtils.isDownloadsDocument
import com.luck.picture.lib.utils.PictureFileUtils.isExternalStorageDocument
import com.luck.picture.lib.utils.PictureFileUtils.isGooglePhotosUri
import com.luck.picture.lib.utils.PictureFileUtils.isMediaDocument
import java.io.File

/**
 * @author:njb
 * @date: 2023/12/4 14:01
 * @desc:文件工具类
 **/
object FileUtils {
    private val TAG: String = FileUtils::class.java.getName()
    /**
     * 从文件路径获取uri
     *
     * @param path 文件路径
     * @return uri
     */
    fun getUriFromPath(path: String?, application: Application?): Uri? {
        val file = File(path)
        return if (file.exists()) {
            application?.let { getUriFromFile(file, it) }
        } else {
            Log.e(TAG, "File is not exist")
            null
        }
    }

    /**
     * 从File获取Uri
     * 此方式获取视频Uri原生视频分享报导入失败，解决方式参考 getVideoUri()
     *
     * @param file 文件
     * @return uri
     */
    fun getUriFromFile(file: File?, application: Application): Uri? {
        val mUri: Uri
        mUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.w("lzq", "name:" + application.packageName)
            FileProvider.getUriForFile(
                application,
                application.packageName + ".fileprovider", file!!
            )
        } else {
            Uri.fromFile(file)
        }
        return mUri
    }

    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param context  上下文
     * @param imageUri 图片地址
     */
    fun getImageAbsolutePath(context: Activity?, imageUri: Uri?): String? {
        if (context == null || imageUri == null) return null
        if (DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                val docId = DocumentsContract.getDocumentId(imageUri)
                val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                val type = split[0]
                if ("primary".equals(type, ignoreCase = true)) {
                    return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                }
            } else if (isDownloadsDocument(imageUri)) {
                val id = DocumentsContract.getDocumentId(imageUri)
                val contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"),
                    id.toLong()
                )
                return getDataColumn(
                    context,
                    contentUri,
                    null,
                    null
                )
            } else if (isMediaDocument(imageUri)) {
                val docId = DocumentsContract.getDocumentId(imageUri)
                val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                val type = split[0]
                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }
                val selection = MediaStore.Images.Media._ID + "=?"
                val selectionArgs = arrayOf(split[1])
                return getDataColumn(
                    context,
                    contentUri,
                    selection,
                    selectionArgs
                )
            }
        } // MediaStore (and general)
        else if ("content".equals(imageUri.scheme, ignoreCase = true)) {
            // Return the remote address
            return if (isGooglePhotosUri(imageUri)) imageUri.lastPathSegment else getDataColumn(
                context,
                imageUri,
                null,
                null
            )
        } else if ("file".equals(imageUri.scheme, ignoreCase = true)) {
            return imageUri.path
        }
        return null
    }


}